package processus;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class ClientEmission extends Thread {
    
    protected int pid;
    protected Tampon tampon;

    public ClientEmission(Tampon tampon, int pid) {
        this.tampon = tampon;
        this.pid = pid;
    }
    
    @Override
    public void run()
    {
        System.out.println("[ClientEmission P"+pid+"] Lancé");
		
        while(true) {

            // On attend des éléments dans le tampon
            String cmd = tampon.retirer();

            // Si on doit s'arrêter
            if(cmd.equals("CLOSE")) {
                break;
            }


            // Sinon on lit la commande (de la forme 'pidSrc,pidDest,estampille,cmd')
            String[] split = cmd.split(",");
            int pidDest = Integer.parseInt(split[1]);

            // On écrit sur la socket
            try {
                Socket socket = new Socket(InetAddress.getLocalHost(), 6000+pidDest);
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                out.println(cmd);
                out.flush();
                socket.close();
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }

        }
        
        System.out.println("[ClientEmission P"+pid+"] Arrété");
    }
    
}